package net.zhengxinyun.performance.controller.indicators;


import com.sirdc.modules.utils.NumberUtils;
import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.Util.WordUtil;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.dto.ExcelDTO;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.CountryIndicatorsFilter;
import net.zhengxinyun.performance.filter.CountryScoreFilter;
import net.zhengxinyun.performance.filter.DepartmentFilter;
import net.zhengxinyun.performance.service.department.DepartmentService;
import net.zhengxinyun.performance.service.exportService.ExcelDtoService;
import net.zhengxinyun.performance.service.exportService.ExportService;
import net.zhengxinyun.performance.service.indicators.CountryIndicatorsService;
import net.zhengxinyun.performance.service.indicators.CountryScoreService;
import net.zhengxinyun.performance.service.leaders.LeaderService;
import net.zhengxinyun.performance.service.login.LoginService;
import net.zhengxinyun.performance.service.login.RolePerService;
import net.zhengxinyun.performance.service.login.TokenService;
import net.zhengxinyun.performance.service.login.UserService;
import net.zhengxinyun.performance.service.report.IndexReportService;
import net.zhengxinyun.performance.service.setTime.SetTimeService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * 县指标控制层
 *
 * @Auther: hyp
 * @Date: 2018/10/26 16:11
 */
@RestController
@RequestMapping("/countryIndicators")
public class CountryIndicatorsController {

    private CountryIndicatorsService countryIndicatorsService;

    private TokenService tokenService;

    private CountryScoreService countryScoreService;

    private UserService userService;

    private LoginService loginService;

    private SetTimeService setTimeService;

    @Autowired
    private RolePerService rolePerService ;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private IndexReportService indexReportService;

    @Autowired
    private ExportService exportService;

    @Autowired
    private ExportService excelService;

    @Autowired
    private ExcelDtoService excelDtoService;
    @Autowired
    private LeaderService leaderService;


    @Autowired
    public CountryIndicatorsController(CountryIndicatorsService countryIndicatorsService, TokenService tokenService, CountryScoreService countryScoreService, UserService userService, LoginService loginService, SetTimeService setTimeService) {
        this.countryIndicatorsService = countryIndicatorsService;
        this.tokenService = tokenService;
        this.countryScoreService = countryScoreService;
        this.userService = userService;
        this.loginService = loginService;
        this.setTimeService = setTimeService;
    }

    /**
     * 指标管理删除
     *
     * @param param
     * @return
     */
    @PostMapping("/delete")
    public Result<String> delete(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            String str = countryIndicatorsService.delete(param.countryIndicatorsEntity);
            if (!"删除成功".equals(str)) {
                return ResultUtils.getResults(Result.Status.ERROR, str);
            } else {
                return ResultUtils.getSuccessResults();
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 指标管理修改
     *
     * @param param
     * @return
     */
    @PostMapping("/update")
    public Result<String> update(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            //根据传来的上级指标名设置上级指标id
            if(ObjectUtils.isNotBlank(param.countryIndicatorsEntity.getLeadNames()))
            {
                String leaders = StringUtils.join(param.countryIndicatorsEntity.getLeadNames(),",");
                param.countryIndicatorsEntity.setLeadName(leaders);
            }else {
                param.countryIndicatorsEntity.setLeadName(null);
            }

//            countryIndicatorsService.setIdByName(param.countryIndicatorsEntity.getSuperiorIndexId(), param.countryIndicatorsEntity.getDateTime(), param.countryIndicatorsEntity);
            int i = countryIndicatorsService.update(param.countryIndicatorsEntity);
            if (i == 1) {
                return ResultUtils.getSuccessResults();
            } else {
                return ResultUtils.getResults(Result.Status.ERROR, "更新失败，请联系管理员");
            }
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 指标管理添加
     *
     * @param param
     * @return
     */
    @PostMapping("/insert")
    public Result<String> insert(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            CountryIndicatorsFilter filter = new CountryIndicatorsFilter();
            if (param.countryIndicatorsEntity != null) {
                CountryIndicatorsEntity countryIndicatorsEntity = param.countryIndicatorsEntity;
                List<String> leadNames = param.countryIndicatorsEntity.getLeadNames();
                if(ObjectUtils.isNotBlank(leadNames)){
                    String leaders = StringUtils.join(leadNames,",");
                    countryIndicatorsEntity.setLeadName(leaders);
                }


                //根据传来的上级指标名设置上级指标id
//                countryIndicatorsService.setIdByName(countryIndicatorsEntity.getSuperiorIndexId(), countryIndicatorsEntity.getDateTime(), countryIndicatorsEntity);
                int i = countryIndicatorsService.insert(countryIndicatorsEntity);
                if (i != 0) {
                    return ResultUtils.getSuccessResults();
                } else {
                    return ResultUtils.getResults(Result.Status.ERROR, "添加失败，请联系管理员");
                }
            } else if (param.list != null) {



                String names ="";

                String resps ="";
                for (CountryIndicatorsEntity countryIndicatorsEntity : param.list) {
                    filter.setIndexName(countryIndicatorsEntity.getIndexName());
                    filter.setDateTime(countryIndicatorsEntity.getDateTime());
                    filter.setIndexType(countryIndicatorsEntity.getIndexType());
                  /*  if (countryIndicatorsService.query(filter).size() != 0) {
                        continue;
                    }
                    if (param.dateTime != null) {
                        countryIndicatorsEntity.setDateTime(param.dateTime);
                    }
                    if (StringUtils.isNotBlank(countryIndicatorsEntity.getSuperiorIndexId())) {
                        //根据传来的上级指标名设置上级指标id
                        countryIndicatorsService.setIdByName(countryIndicatorsEntity.getSuperiorIndexId(), countryIndicatorsEntity.getDateTime(), countryIndicatorsEntity);
                    }*/
                  if("二级指标".equals(countryIndicatorsEntity.getIndexType()))
                  {
                     String departName = countryIndicatorsEntity.getLeadUnit();
                     DepartmentEntity depart = departmentService.getDepartByName(departName);
                     if(ObjectUtils.isBlank(depart))
                     {
                         names=names+ departName+",";
                         continue;
                     }
                      countryIndicatorsEntity.setLeadUnit(depart.getDepartcode());
                      departName=countryIndicatorsEntity.getResponsibilityUnit();
                      depart = departmentService.getDepartByName(departName);
                      if(ObjectUtils.isBlank(depart))
                      {
                          resps=resps+ departName+",";
                          continue;
                      }
                      countryIndicatorsEntity.setResponsibilityUnit(depart.getDepartcode());
                      int i = countryIndicatorsService.insert(countryIndicatorsEntity);
                      if (i == 0) {
                          return ResultUtils.getResults(Result.Status.ERROR, "添加失败，请联系管理员");
                      }
                  }





                }
                return ResultUtils.getSuccessResults();
            }
            return ResultUtils.getResults(Result.Status.ERROR);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }


    /**
     * 指标管理查询
     *
     * @param param
     * @return
     */
    @PostMapping("/query")
    public Result<HashMap<String, Object>> query(@RequestBody CountryIndicatorsParam param, HttpServletRequest request) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            if (param.countryIndicatorsFilter.getPageSize() == 0) {
                param.countryIndicatorsFilter.setPageSize(10);
            }

            String year=null;
            if(StringUtils.isBlank(param.countryIndicatorsFilter.getDateTime()))
            {
                year= (String) request.getSession().getAttribute("currentYear");
                if(year==null)
                {
                    return ResultUtils.getResults(Result.Status.OVERTIME,"登录超时，请重新登录",null);
                }
                param.countryIndicatorsFilter.setDateTime(year);
            }

            HashMap<String, Object> map = new HashMap<>();
            CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
            countryIndicatorsFilter.setIndexType("一级指标");
            countryIndicatorsFilter.setDateTime(year);
            List<CountryIndicatorsFilter> firstIndexList = countryIndicatorsService.query(countryIndicatorsFilter);
            map.put("firstIndex", firstIndexList);//给一级指标集合

            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            /*
                市对县指标，超级管理员可以看全部，非超级管理只能看自己牵头的指标。
                判断不是超级管理员，就设置牵头单位的code去筛选
             */
          /*
            不需要按照牵头单位来县直，按照勾选指标筛选
           if (!"admin".equals(userEntity.getUserPermissions()))
            {
                param.countryIndicatorsFilter.setLeadUnit(userEntity.getDepartcode());
            }
            */
            //param.countryIndicatorsFilter.setLeadUnit();




            List<CountryIndicatorsFilter> list = countryIndicatorsService.query(param.countryIndicatorsFilter);
            if (list.size() == 0) {
                param.countryIndicatorsFilter.setPageNumber(param.countryIndicatorsFilter.getPageNumber() - 1);
                list = countryIndicatorsService.query(param.countryIndicatorsFilter);
            }



          String index ="";
          RolePerEntity rolePerEntity  = rolePerService.selectByPrimaryKey(userEntity.getRoleid());
          if(ObjectUtils.isNotBlank(rolePerEntity))
          {
              index = rolePerEntity.getCityIndex();
          }else {
              index = userEntity.getCityIndex();
          }
          HashMap<String,Object> indexmap = Util.getIndexIdMap(index);
            List<CountryIndicatorsFilter> list2 = new ArrayList<>();
            for (CountryIndicatorsFilter item : list)
            {

                String leadName = item.getLeadName();
               /* if (StringUtils.isNotBlank(leadName))
                {

                }*/
                List<String> strings = Util.strToList(leadName);
                item.setLeadNames(strings);

                String idone = item.getId().toString();
              Object idtwo = indexmap.get(idone);
              if(ObjectUtils.isBlank(idtwo))
              {
                  continue;
              }
              if(idone.equals(idtwo.toString()))
              {
                  list2.add(item);
              }


            }

            map.put("list", list2);//根据条件查询集合
            if("admin".equals(userEntity.getUserPermissions()))
            {
                map.put("list", list);//根据条件查询集合
            }
            Double pageTotal = Util.intGetTotalPage(countryIndicatorsService.queryForCount(param.countryIndicatorsFilter), param.countryIndicatorsFilter.getPageSize());
            map.put("pageTotal", pageTotal);

           /* List<LeadersEntity> leadersEntities = leaderService.queryAll(new LeadersEntity());
            map.put("leaderinfo",leadersEntities);*/

            return ResultUtils.getSuccessResults(map);
        }

        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 录入分数页查询
     *
     * @param param
     * @return
     */
    @PostMapping("/queryInspection")
    public Result<HashMap<String, Object>> queryInspection(@RequestBody CountryIndicatorsParam param,HttpServletRequest request) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            if (param.countryIndicatorsFilter.getPageSize() == 0) {
                param.countryIndicatorsFilter.setPageSize(10);
            }
            HashMap<String, Object> map = new HashMap<>();
            CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
            countryIndicatorsFilter.setIndexType("一级指标");
            List<CountryIndicatorsFilter> firstIndexList = countryIndicatorsService.query(countryIndicatorsFilter);
            List<Map<String, Object>> indexList = countryIndicatorsService.getIndexMap(firstIndexList);
            map.put("indexMap", indexList);
            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
           /*不需要按照牵头单位来县直， 按照勾选的指标去筛选
            if (!"admin".equals(userEntity.getUserPermissions())) {
                param.countryIndicatorsFilter.setLeadUnit(userEntity.getDepartcode());
            }*/


            String year= (String) request.getSession().getAttribute("currentYear");
            if(year==null)
            {
                return ResultUtils.getResults(Result.Status.OVERTIME,"登录超时，请重新登录",null);
            }
            if(StringUtils.isBlank(param.countryIndicatorsFilter.getDateTime()))
            {
                param.countryIndicatorsFilter.setMonthTime(DateUtils.getLastMonth(year));   //  设置年月
                param.countryIndicatorsFilter.setDateTime(year);  //  设置年份
            }else {
                param.countryIndicatorsFilter.setMonthTime(DateUtils.getLastMonth(param.countryIndicatorsFilter.getDateTime()));
            }


            List<CountryIndicatorsFilter> list = countryIndicatorsService.querySecondIndex(param.countryIndicatorsFilter,userEntity);
            if (list.size() == 0) {
                param.countryIndicatorsFilter.setPageNumber(param.countryIndicatorsFilter.getPageNumber() - 1);
                list = countryIndicatorsService.querySecondIndex(param.countryIndicatorsFilter,userEntity);
            }
            try {
                //判断当前时间是否可填写分数
                SetTimeEntity setTimeEntity = setTimeService.findByIndexClass("2");
                String startTime = setTimeEntity.getStartTime();
                String endTime = setTimeEntity.getEndTime();

                int start = Integer.parseInt(startTime);
                int end = Integer.parseInt(endTime);
                Date date = new Date();
                //获取当前日
                int date1 = date.getDate();
                if ("1".equals(setTimeEntity.getIsThisMonth())) {
                    if (date1 >= start && date1 <= end) {
                        map.put("status", "1");
                    } else {
                        map.put("status", "0");
                    }
                }
                if ("2".equals(setTimeEntity.getIsThisMonth())) {
                    if (date1 >= start || date1 <= end) {
                        map.put("status", "1");
                    } else {
                        map.put("status", "0");
                    }

                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

           // Double pageTotal = Util.intGetTotalPage(countryIndicatorsService.queryByTwoTableCount(param.countryIndicatorsFilter), param.countryIndicatorsFilter.getPageSize());
          //  map.put("pageTotal", pageTotal);
            map.put("list", list);
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    @PostMapping("/queryAudit")
    public Result<HashMap<String, Object>> queryAudit(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            if (param.countryIndicatorsFilter.getPageSize() == 0) {
                param.countryIndicatorsFilter.setPageSize(10);
            }
            HashMap<String, Object> map = new HashMap<>();
            CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
            countryIndicatorsFilter.setIndexType("一级指标");
            List<CountryIndicatorsFilter> firstIndexList = countryIndicatorsService.query(countryIndicatorsFilter);
            List<Map<String, Object>> indexList = countryIndicatorsService.getIndexMap(firstIndexList);
            map.put("indexMap", indexList);
            UserEntity userEntity = loginService.getUserByToken(param.tokenEntity);
            if (!"admin".equals(userEntity.getUserPermissions())) {
                param.countryIndicatorsFilter.setLeadUnit(userEntity.getUserDepartment());
            }

            List<CountryIndicatorsFilter> list = countryIndicatorsService.queryForAudit(param.countryIndicatorsFilter);
            if (list.size() == 0) {
                param.countryIndicatorsFilter.setPageNumber(param.countryIndicatorsFilter.getPageNumber() - 1);
                list = countryIndicatorsService.queryForAudit(param.countryIndicatorsFilter);
            }
            Double pageTotal = Util.intGetTotalPage(countryIndicatorsService.queryForAuditCount(param.countryIndicatorsFilter), param.countryIndicatorsFilter.getPageSize());
            map.put("pageTotal", pageTotal);
            map.put("list", list);
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 录入分数
     *
     * @param param
     * @return
     */
    @PostMapping("/insertScore")
    public Result<String> setScore(@RequestBody CountryIndicatorsParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            UserEntity user = loginService.getUserByToken(param.tokenEntity);


            int i = 0;
            CountryScoreEntity countryScoreEntity = new CountryScoreEntity();
            //因为前端不想改传过来的对象，只能后台赋值
            countryScoreEntity.setIndicatorsId(param.countryIndicatorsEntity.getId().toString());
            countryScoreEntity.setDateTime(param.countryIndicatorsEntity.getDateTime());
            countryScoreEntity.setFinalScore(param.countryIndicatorsEntity.getFinalScore());
            countryScoreEntity.setDepartcode(param.countryIndicatorsEntity.getLeadUnit());
            countryScoreEntity.setRank(param.countryIndicatorsEntity.getRank());
            countryScoreEntity.setProblems(param.countryIndicatorsEntity.getProblems());
            countryScoreEntity.setIndexProgress(param.countryIndicatorsEntity.getIndexProgress());
            countryScoreEntity.setAudit("1");
            countryScoreEntity.setVaild(1);
            CountryScoreEntity  cityScore = countryScoreService.selectCityScore(param.countryIndicatorsEntity.getId().toString(),
                    param.countryIndicatorsEntity.getDepartcode(),DateUtils.getLastMonth() );
            if(ObjectUtils.isNotBlank(cityScore))
            {
                cityScore.setVaild(0);

                countryScoreService.update(cityScore);

            }


            int weight  =param.countryIndicatorsEntity.getWeight();
           // double rate = (countryScoreEntity.getFinalScore()/ weight) *100;
            double rate = StringUtils.toDouble(param.countryIndicatorsEntity.getScore());
            countryScoreEntity.setScore(param.countryIndicatorsEntity.getScore());
            //计算得分  得分 = 权重x得分率/100
            double finalScore = weight*rate/100;
            String score = NumberUtils.keepPrecision(finalScore,2);
            countryScoreEntity.setFinalScore(StringUtils.toDouble(score));
            String  rates = NumberUtils.keepPrecision(rate,2);
            countryScoreEntity.setScore(Double.parseDouble(rates));
            i = countryScoreService.insert(countryScoreEntity);
            if (i == 0) {
                    return ResultUtils.getResults(Result.Status.ERROR, "添加失败");
            }
            //*保存到报送情况表

            indexReportService.saveReport(user,1,param.countryIndicatorsEntity.getId(),param.countryIndicatorsEntity.getDateTime());


            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    /**
     * 导出市对县汇总表
     * @param reponse
     * @param datetime
     */
    @GetMapping("/exportDate")
    public void  exprotCityIndexDate(HttpServletResponse reponse,String datetime,String orderBy)
    {
        if(StringUtils.isBlank(datetime))
        {
            datetime= DateUtils.getCurrentMonth();
        }

        XSSFWorkbook cityIndexDate = exportService.getCityIndexDate(datetime,orderBy);

        OutputStream out = null;

        try {
            out=reponse.getOutputStream();
            String fileName  = "市对县指标汇总表.xlsx";
            reponse.setContentType("application/x-msdownload");
            reponse.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            cityIndexDate.write(out);

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * \
     * 市对县指标分析报告 导出word
     * @param reponse
     * @param datetime
     * @param topNum
     */
    @GetMapping("/cityIndexReport")
    public void cityIndexReport(HttpServletResponse reponse,String datetime,int topNum){


        HashMap<String, Object> map = exportService.getCityIndexReport(datetime, topNum);
        map.put("datetime",datetime);
        map.put("topNum",topNum);

        try {
            WordUtil.exportWrodFile(reponse,map,"cityIndexReport.ftl","市对县指标分析报告.doc");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    /**
     * 市对县指标管理导入
     */
    @PostMapping("/uploadCityIndex")
    public  Result<HashMap<String,Object>> uploadCityIndex(@RequestParam(value = "file") MultipartFile file){
        if(file ==null)
        {

            return ResultUtils.getResults(Result.Status.ERROR, "上传失败，上传文件不能为空", null);
        }
        String fileName = file.getOriginalFilename();

        if(!fileName.matches("^.+\\.(?i)(xls)$")&&!fileName.matches("^.+\\.(?i)(xlsx)$")){
            return ResultUtils.getResults(Result.Status.ERROR, "上传失败，文件格式错误",null);
        }

        HashMap<String,Object> map  =  excelService.uploadCityIndex(file);

        if((int) map.get("code")==200)
        {
            return ResultUtils.getSuccessResults(map);
        }else {
            return  ResultUtils.getResults(Result.Status.ERROR, map.get("message")+"",null);
        }
    }


 /*   @PostMapping("/queryAfter")
    public Result<HashMap<String, Object>> queryData(@RequestBody CountryIndicatorsParam param ){
        String batchNum = param.excelDTO.getBatchNum();
        if(StringUtils.isBlank(batchNum))
        {
            return ResultUtils.getResults(Result.Status.ERROR, "导入批次号为空", null);
        }
        List<ExcelDTO> dtoList = excelDtoService.queryData(batchNum,null);
        List<ExcelDTO> collect = dtoList.stream().filter(dto -> 0==dto.getAvail()).collect(Collectors.toList());
        HashMap<String,Object> map = new HashMap<>();
        map.put("list",dtoList);
        if (collect.size()>0){
            map.put("warn","当前数据有"+collect.size()+"条警告信息。");
        }else {
            map.put("warn","校验通过，无警告数据，可直接上传数据");
        }

        return ResultUtils.getSuccessResults(map);
    }*/



    /**
     * 保存导入
     * @param param
     * @return
     */
    @PostMapping("/saveExcelData")
    public Result<String> saveExcelData(@RequestBody CountryIndicatorsParam param)
    {

        String datetime = param.excelDTO.getDatetime();
        String batchNum = param.excelDTO.getBatchNum();
        if(StringUtils.isBlank(batchNum)|| StringUtils.isBlank(datetime))
        {
            return  ResultUtils.getResults(Result.Status.ERROR,"批次号或者导入日期为空，请重新操作");
        }
        List<ExcelDTO> dtoList = excelDtoService.queryData(batchNum,1);

         int i =countryIndicatorsService.saveExcelCityIndex(dtoList,datetime);
        if(i==0)
        {
            return  ResultUtils.getResults(Result.Status.ERROR,"导入失败，请根据导入批次号联系管理员");
        }

        return  ResultUtils.getSuccessResults();

    }

    // 市对县指标分析




}

class CountryIndicatorsParam {
    public CountryIndicatorsFilter countryIndicatorsFilter;
    public CountryIndicatorsEntity countryIndicatorsEntity;
    public ExcelDTO excelDTO;
    public TokenEntity tokenEntity;
    public List<CountryIndicatorsEntity> list;
    public String dateTime;
    public CountryScoreEntity countryScoreEntity;
    public CountryScoreFilter countryScoreFilter;
}
